<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="作品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入岗位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="作品类别" prop="category">
        <el-select
          v-model="queryParams.category"
          placeholder="作品类别"
          clearable
        >
          <el-option
            v-for="dict in dict.type.work_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:project:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['system:project:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleDelete" v-hasPermi="['system:project:remove']">删除</el-button>
            </el-col> -->

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectList">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="作品名称" align="center" prop="name" />
      <el-table-column label="作品类别" align="center" prop="category">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.work_type"
            :value="scope.row.category"
          />
        </template>
      </el-table-column>
      <el-table-column label="所属区域" align="center" prop="addressContent" />
      <el-table-column label="辅导老师" align="center" prop="tutorName" />
      <el-table-column
        label="辅导老师联系方式"
        align="center"
        prop="tutorContact"
      />

      <el-table-column
        label="作品简介"
        align="center"
        prop="description"
        width="180"
        show-overflow-tooltip
      />
      <el-table-column label="活动对象" align="center" prop="participantType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.grade"
            :value="scope.row.participantType"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="活动人数"
        align="center"
        prop="participantCount"
      />
      <el-table-column label="得分" align="center" prop="score" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetail(scope.row)"
            v-hasPermi="['system:project:detail']"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:project:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleSetScore(scope.row)"
            v-hasPermi="['system:project:score']"
            >打分</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:project:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        label-position="top"
        :disabled="handleType === 'detail'"
      >
        <el-row :gutter="34">
          <el-col :span="12">
            <el-form-item label="作品类别" prop="category">
              <el-select
                style="width: 100%"
                v-model="form.category"
                placeholder="作品类别"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.work_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="所属区域" prop="district">
              <el-cascader
                style="width: 100%"
                v-model="form.district"
                :options="addressOptions"
                :props="{ label: 'name', value: 'id' }"
                ref="cascaderRef"
                @change="handleOnAddressChange"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="辅导老师联系方式" prop="tutorContact">
              <el-input
                v-model="form.tutorContact"
                placeholder="请输入联系方式"
              />
            </el-form-item>

            <el-form-item label="活动对象" prop="participantType">
              <el-select
                style="width: 100%"
                v-model="form.participantType"
                placeholder="活动对象"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.grade"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="活动人数" prop="participantCount">
              <el-input-number
                style="width: 100%"
                v-model="form.participantCount"
                controls-position="right"
                :min="1"
                :max="3"
                :controls="false"
                placeholder="请输入活动人数"
              />
            </el-form-item>
            <el-form-item label="作品简介" prop="description">
              <el-input
                v-model="form.description"
                placeholder="作品简介"
                type="textarea"
                maxlength="500"
                :rows="3"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入岗位名称" />
            </el-form-item>
            <el-form-item label="辅导老师" prop="tutorName">
              <el-input v-model="form.tutorName" placeholder="请输入编码名称" />
            </el-form-item>
            <el-form-item label="创作档案/演示视频" prop="creationFile">
              <!-- :fileType="['mp4']" -->
              <FileUpload
                :fileSize="500"
                :limit="1"
                :fileType="['mp4']"
                :value="form.creationFile"
                :disabled="handleType === 'detail'"
                @input="handleChangeFile($event, 'creationFile')"
              />
            </el-form-item>
            <el-form-item label="作品" prop="workUrl">
              <template v-if="form.category != '2'">
                <!-- :fileType="fileType" -->
                <FileUpload
                  :fileSize="form.category == '1' ? 20 : 100"
                  :value="form.workUrl"
                  :limit="1"
                  :fileType="fileType"
                  @input="handleChangeFile($event, 'workUrl')"
                  :disabled="handleType === 'detail'"
                />
              </template>
              <template v-else>
                <el-input v-model="form.workUrl" placeholder="请输入作品链接" />
              </template>
            </el-form-item>
            <el-form-item label="创作者声明" prop="creatorStatement">
              <FileUpload
                :fileSize="20"
                :limit="1"
                :value="form.creatorStatement"
                :isShowTip="false"
                :disabled="handleType === 'detail'"
                @input="handleChangeFile($event, 'creatorStatement')"
              />
              <el-button type="text" :disabled="false" @click="importTemplate"
                >下载模版</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="handleType !== 'detail'">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="打分"
      :visible.sync="scoreOpen"
      width="450px"
      append-to-body
    >
      <el-form
        ref="form1"
        :model="form1"
        :rules="rules1"
        label-width="80px"
        label-position="top"
      >
        <el-form-item label="评分" prop="score">
          <el-input-number
            style="width: 100%"
            v-model="form1.score"
            controls-position="right"
            :min="0"
            :controls="false"
            placeholder="请输入评分"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="scoreOpen = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveScore">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  apiGetProjectList,
  apiGetProjectDetail,
  apiDeleteProject,
  apiAddProject,
  apiUpdateProject,
  apiDownloadTemplate,
} from "@/api/projectManage";
import FileUpload from "@/components/FileUpload/index.vue";
import { apiGetAreaTreeList } from "@/api/system/user";

export default {
  name: "Post",
  dicts: ["work_type", "grade"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      scoreOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        category: undefined,
        name: undefined,
      },
      // 表单参数
      form: {
        category: "1",
      },
      form1: {
        score: undefined,
      },
      // 表单校验
      rules: {
        district: [
          // { required: true, message: "所属区域不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "作品名称不能为空", trigger: "blur" },
        ],
        participantType: [
          { required: true, message: "活动对象不能为空", trigger: "blur" },
        ],
        tutorName: [
          { required: true, message: "辅导老师不能为空", trigger: "blur" },
        ],
        tutorContact: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        creationFile: [
          {
            required: true,
            message: "创作档案/演示视频不能为空",
            trigger: "blur",
          },
        ],
        workUrl: [{ required: true, message: "作品不能为空", trigger: "blur" }],
        creatorStatement: [
          { required: true, message: "创作者声明不能为空", trigger: "blur" },
        ],
      },
      rules1: {
        score: [{ required: true, message: "评分不能为空", trigger: "blur" }],
      },
      addressOptions: [],
      handleType: "",
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      apiGetProjectList(this.queryParams).then((response) => {
        this.projectList = response.data?.list || [];
        this.total = response.data?.total ?? 0;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        district: [],
        category: "1",
        tutorContact: undefined,
        participantType: undefined,
        participantCount: undefined,
        description: undefined,
        name: undefined,
        tutorName: undefined,
        creationFile: undefined,
        creatorStatement: undefined,
        workUrl: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    async handleAdd() {
      await this.laodAddressOptionsa();
      this.reset();
      this.handleType = "add";
      this.open = true;
      this.title = "新增项目";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      this.handleType = "edit";
      await this.laodAddressOptionsa();
      const id = row.id;
      apiGetProjectDetail(id).then((response) => {
        this.form = {
          ...response.data,
          district:
            response.data?.district && response.data.district.split(","),
        };
        this.open = true;
        this.title = "修改项目";
      });
    },

    async handleDetail(row) {
      this.reset();
      this.handleType = "detail";
      await this.laodAddressOptionsa();
      const id = row.id;
      apiGetProjectDetail(id).then((response) => {
        this.form = {
          ...response.data,
          district:
            response.data?.district && response.data.district.split(","),
        };
        this.open = true;
        this.title = "查看";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const { district } = this.form;
          let params = {
            ...this.form,
            district: district.length > 0 ? district.join(",") : undefined,
          };
          if (this.form.id != undefined) {
            apiUpdateProject(params).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            apiAddProject(params).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleSetScore(row) {
      this.form1.id = row.id;
      this.scoreOpen = true;
      this.form1.score = undefined;
    },
    handleSaveScore() {
      this.$refs["form1"].validate((valid) => {
        if (valid) {
          let params = {
            ...this.form1,
            score: this.form1.score,
          };
          apiUpdateProject(params).then((response) => {
            this.$modal.msgSuccess("打分成功");
            this.scoreOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.id;
      const $this = this;
      this.$modal.confirm("是否确认删除？").then(async function () {
        const { code } = await apiDeleteProject(postIds);
        if (code === 200) {
          $this.getList();
          $this.$modal.msgSuccess("删除成功");
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/post/export",
        {
          ...this.queryParams,
        },
        `post_${new Date().getTime()}.xlsx`
      );
    },
    async laodAddressOptionsa() {
      const { data, code } = await apiGetAreaTreeList();
      if (code !== 200) return;
      this.addressOptions = data;
    },
    handleOnAddressChange() {
      console.log(
        this.$refs.cascaderRef
          .getCheckedNodes()[0]
          ?.pathNodes.map((item) => item.label)
          .join("/")
      );
      this.form.addressContent = this.$refs.cascaderRef
        .getCheckedNodes()[0]
        ?.pathNodes.map((item) => item.label)
        .join("/");
    },
    handleChangeFile(value, props) {
      this.form[props] = value;
    },
    async importTemplate() {
      const { code, data } = await apiDownloadTemplate();
      if (code == 200 && data) {
        const cleanedUrl = new URL(data, window.location.href).href;
        const a = document.createElement("a");
        a.href = cleanedUrl;
        a.target = "_blank";
        a.download = "创作者声明模版";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      }
    },
  },
  computed: {
    fileType() {
      let fileTypeMap = {
        1: ["png", "jpg", "jpeg"],
        3: ["doc", "docx"],
        5: ["doc", "docx"],
        4: ["pdf"],
      };
      return fileTypeMap[this.form.category];
    },
  },
};
</script>